﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Security.Permissions;
using System.Web;
using System.Web.UI;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.WebControls;
using TemplateLibraryConnector.Data;
using TemplateLibraryConnector.Utility;
using TemplateLibraryConnector.UI;


namespace TemplateLibraryConnector.ServerControls
{
    [SharePointPermission(SecurityAction.InheritanceDemand, ObjectModel = true),
     AspNetHostingPermission(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal),
     SharePointPermission(SecurityAction.LinkDemand, ObjectModel = true),
     AspNetHostingPermission(SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
    public class ViewSelector : ViewStateEnabledToolBarMenuButton, IPostBackEventHandler
    {
        
        #region Properties

        public const string RequestParamViewId = "ViewID";
        
        public SPView SelectedView { get; set; }

        [PersistToViewState]
        public Guid SelectedViewId { get; set; }

        [PersistToViewState]
        public List<KeyValuePair<Guid, string>> MenuItems { get; set; }

        public override string Text
        {
            get
            {
                return SelectedView != null ? SelectedView.Title : base.Text;
            }
        }

        #endregion

        public event EventHandler SelectedViewChanged;

        
        #region IPostBackEventHandler Members

        public void RaisePostBackEvent(string eventArgument)
        {
            if (!string.IsNullOrEmpty(eventArgument))
            {
                SelectedViewId = new Guid(eventArgument);
                SetSelectedView();

                if (SelectedViewChanged != null)
                    SelectedViewChanged(this, EventArgs.Empty);
            
            }
        }

        #endregion

        protected override void AddMenuItems()
        {
            var templateHubController = new TemplateHubController((this.Page as Selector).DestinationLibraryUrl);
            var templateHubUrl = templateHubController._settings.GetTemplateHubAddress(string.Empty);
            var listId = new Guid(templateHubController._settings.TemplateListIds);
            using (var templateHubSite = TemplateLibraryDataUtility.GetDocumentLibrarySite(templateHubUrl))
            {
                using (var templateHubWeb = TemplateLibraryDataUtility.GetDocumentLibraryWebFromUrl(templateHubUrl, templateHubSite))
                {
                    var docLib = templateHubWeb.Lists[listId] as SPDocumentLibrary;
                    if (docLib != null)
                    {
                        var views = docLib.Views;

                        if (views != null)
                        {
                            MenuItems = new List<KeyValuePair<Guid, string>>();
                            foreach (var view in views.Cast<SPView>().Where(view => !view.DefaultView && !view.Hidden && String.IsNullOrEmpty(view.ModerationType) && view.Type == "HTML"))
                            {
                                MenuItems.Add(new KeyValuePair<Guid, string>(view.ID, view.Title));
                            }
                        }
                    }
                    if (MenuItems != null)
                    {
                        MenuTemplateControl.Controls.Clear();
                        foreach (var menuItemTemplate in MenuItems)
                        {
                            AddViewMenuItem(menuItemTemplate.Value, menuItemTemplate.Key.ToString(), 0);
                        }
                    }
                }
            }
        }


        private void AddViewMenuItem(string text, string urlParameters, int sequence)
        {
            var child = new MenuItemTemplate
                       {
                           MenuGroupId = 100,
                           Sequence = sequence,
                           Text = text,
                           UseShortId = true,
                           ClientOnClickScript =
                               string.Format("__doPostBack('{0}','{1}')", UniqueID, urlParameters)
                           
                       };
            MenuTemplateControl.Controls.Add(child);
        }


        [SharePointPermission(SecurityAction.Demand, ObjectModel = true)]
        protected override void CreateChildControls()
        {
         
            if (string.IsNullOrEmpty(AccessKey))
            {
                AccessKey = SPResource.GetString("ViewSelectorMenuOpenAK", new object[0]);
            }
                
            base.CreateChildControls();
            
            MenuControl.HoverCellActiveCssClass = "ms-viewselectorhover";
            MenuControl.HoverCellInActiveCssClass = "ms-viewselector";
            
        }

        protected override void OnLoad(EventArgs e)
        {
            SetSelectedView();
        }

        private void SetSelectedView()
        {
            if (SelectedView != null && SelectedView.ID == SelectedViewId)
                return;

            var templateHubController = new TemplateHubController((this.Page as Selector).DestinationLibraryUrl);
            var templateHubUrl = templateHubController._settings.GetTemplateHubAddress(string.Empty);

            foreach (string TemplateListId in templateHubController._settings.TemplateListIds.Split(','))
            {
                var listId = new Guid(TemplateListId);
                using (var templateHubSite = TemplateLibraryDataUtility.GetDocumentLibrarySite(templateHubUrl))
                {
                    using (var templateHubWeb = TemplateLibraryDataUtility.GetDocumentLibraryWebFromUrl(templateHubUrl, templateHubSite))
                    {
                        var docLib = templateHubWeb.Lists[listId] as SPDocumentLibrary;
                        if (docLib != null)
                        {
                            var stdView =
                                docLib.Views.Cast<SPView>().FirstOrDefault(view => !view.DefaultView && !view.Hidden && string.IsNullOrEmpty(view.ModerationType) && view.Type == "HTML") ??
                                docLib.Views.List.DefaultView;

                            var selectedView = SelectedViewId != Guid.Empty ? docLib.Views[SelectedViewId] : stdView;

                            SelectedViewId = selectedView.ID;
                            SelectedView = selectedView;
                        }

                        if (SelectedView != null)
                            Text = SelectedView.Title;

                        if (MenuControl != null)
                        {
                            MenuControl.Text = Text;
                        }
                    }
                }
            }
        }
        
    }
}